﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WeatherBar2.Properties;
using Microsoft.WindowsAPICodePack.Taskbar;
using Microsoft.WindowsAPICodePack.Shell;
using System.IO;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Diagnostics;

namespace WeatherBar2
{
    public partial class Main : Form
    {
        int IconID;
        int IconID_FA;
        int IconID_FB;
        int IconID_FC;
        int IconID_FD;

        JumpList jumpList;

        [DllImport("shell32.dll", SetLastError = true)]
        static extern IntPtr ExtractIcon(IntPtr hInst, string lpszExeFileName, int nIconIndex);

        public Main()
        {
            InitializeComponent();

            this.Shown += new EventHandler(Main_Shown);
            pictureBox2.MouseHover += new EventHandler(pictureBox2_MouseHover);
            pictureBox2.MouseLeave += new EventHandler(pictureBox2_MouseLeave);
            pictureBox15.MouseHover += new EventHandler(pictureBox15_MouseHover);
            pictureBox16.MouseHover += new EventHandler(pictureBox16_MouseHover);
            pictureBox15.MouseLeave += new EventHandler(pictureBox15_MouseLeave);
            pictureBox16.MouseLeave += new EventHandler(pictureBox16_MouseLeave);
            pictureBox17.MouseHover += new EventHandler(pictureBox17_MouseHover);
            pictureBox17.MouseLeave += new EventHandler(pictureBox17_MouseLeave);
            DataReloader.RunWorkerCompleted += new RunWorkerCompletedEventHandler(DataReloader_RunWorkerCompleted);
        }

        void Main_Shown(object sender, EventArgs e)
        {
            jumpList = JumpList.CreateJumpList();
        }

        void pictureBox17_MouseLeave(object sender, EventArgs e)
        {
            pictureBox17.Image = Resources.settings_2;
        }

        void pictureBox17_MouseHover(object sender, EventArgs e)
        {
            pictureBox17.Image = Resources.settings;
        }

        void pictureBox16_MouseLeave(object sender, EventArgs e)
        {
            pictureBox16.Image = Resources.exit_2;
        }

        void pictureBox15_MouseLeave(object sender, EventArgs e)
        {
            pictureBox15.Image = Resources.about_2;
        }

        void pictureBox16_MouseHover(object sender, EventArgs e)
        {
            pictureBox16.Image = Resources.exit;
        }

        void pictureBox15_MouseHover(object sender, EventArgs e)
        {
            pictureBox15.Image = Resources.about;
        }

        void pictureBox2_MouseLeave(object sender, EventArgs e)
        {
            pictureBox2.Image = Resources.modify_2;
        }

        void pictureBox2_MouseHover(object sender, EventArgs e)
        {
            pictureBox2.Image = Resources.modify;
        }

        private void pictureBox2_Click(object sender, EventArgs e)
        {
            ChangeLocation changeLocation = new ChangeLocation();
            RefreshTimer.Enabled = false;
            changeLocation.ShowDialog(this);
            RefreshTimer.Enabled = true;
        }

        private void pictureBox17_Click(object sender, EventArgs e)
        {
            Settings settings = new Settings();
            RefreshTimer.Enabled = false;
            settings.ShowDialog(this);
            RefreshTimer.Enabled = true;
        }

        private void Main_Load(object sender, EventArgs e)
        {
            lblLocation.Text = Properties.Settings.Default.Location;

            if (!string.IsNullOrEmpty(Properties.Settings.Default.Location.Trim()))
            {
                pnlRefresh.Visible = true;
                DataReloader.RunWorkerAsync();
            }

            RefreshTimer.Interval = Properties.Settings.Default.UpdateTime * 60000;
        }

        public void DoWork()
        {
            DataReloader.RunWorkerAsync();
        }

        Dictionary<string, string> data = new Dictionary<string, string>();

        void DataReloader_DoWork(object sender, DoWorkEventArgs e)
        {
            data = new Dictionary<string,string>();
            data = Helper.GetData(Properties.Settings.Default.Location);
        }

        void DataReloader_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            pnlRefresh.Visible = false;
            
            if (data != null)
            {
                try
                {
                    lblLocation.Text = data["location"];
                    lblHumidity.Text = data["current_humidity"].Substring(10, data["current_humidity"].Length - 10);
                    lblFDA.Text = data["forecast_day0_dow"];
                    lblFDB.Text = data["forecast_day1_dow"];
                    lblFDC.Text = data["forecast_day2_dow"];
                    lblFDD.Text = data["forecast_day3_dow"];

                    string unitsys = data["unitsys"];

                    if (unitsys.ToUpper() == "US")
                    {
                        if (Properties.Settings.Default.IsMetric)
                        {
                            // -- Wind calculation --
                            string wind = data["current_wind"];
                            int loc = wind.IndexOf("at");
                            int locUnit = wind.IndexOf("mph");

                            int wValue = Convert.ToInt32(wind.Substring(loc + 3, wind.Length - (loc + 3) - 4));
                            double metricWind = wValue * 1.61;

                            wind = wind.Replace(wind.Substring(loc + 3, wind.Length - (loc + 3) - 4), metricWind.ToString());
                            wind = wind.Replace("mph", "kmh");
                            lblWind.Text = wind.Substring(6,wind.Length-6);
                            // -- End of wind calculation --

                            lblTemperature.Text = data["current_tempc"];

                            lblLA.Text = Convert.ToInt32((Convert.ToInt32(data["forecast_day0_low"]) - 32) * 0.55).ToString();
                            lblHA.Text = Convert.ToInt32((Convert.ToInt32(data["forecast_day0_high"]) - 32) * 0.55).ToString();
                            lblLB.Text = Convert.ToInt32((Convert.ToInt32(data["forecast_day1_low"]) - 32) * 0.55).ToString();
                            lblHB.Text = Convert.ToInt32((Convert.ToInt32(data["forecast_day1_high"]) - 32) * 0.55).ToString();
                            lblLC.Text = Convert.ToInt32((Convert.ToInt32(data["forecast_day2_low"]) - 32) * 0.55).ToString();
                            lblHC.Text = Convert.ToInt32((Convert.ToInt32(data["forecast_day2_high"]) - 32) * 0.55).ToString();
                            lblLD.Text = Convert.ToInt32((Convert.ToInt32(data["forecast_day3_low"]) - 32) * 0.55).ToString();
                            lblHD.Text = Convert.ToInt32((Convert.ToInt32(data["forecast_day3_high"]) - 32) * 0.55).ToString();
                        }
                        else
                        {
                            lblWind.Text = data["current_wind"].Substring(6, data["current_wind"].Length - 6);
                            lblTemperature.Text = data["current_tempf"];

                            lblLA.Text = data["forecast_day0_low"];
                            lblHA.Text = data["forecast_day0_high"];
                            lblLB.Text = data["forecast_day1_low"];
                            lblHB.Text = data["forecast_day1_high"];
                            lblLC.Text = data["forecast_day2_low"];
                            lblHC.Text = data["forecast_day2_high"];
                            lblLD.Text = data["forecast_day3_low"];
                            lblHD.Text = data["forecast_day3_high"];
                        }
                    }
                    else
                    {
                        if (Properties.Settings.Default.IsMetric)
                        {
                            lblWind.Text = data["current_wind"].Substring(6, data["current_wind"].Length - 6);
                            lblTemperature.Text = data["current_tempc"];

                            lblLA.Text = data["forecast_day0_low"];
                            lblHA.Text = data["forecast_day0_high"];
                            lblLB.Text = data["forecast_day1_low"];
                            lblHB.Text = data["forecast_day1_high"];
                            lblLC.Text = data["forecast_day2_low"];
                            lblHC.Text = data["forecast_day2_high"];
                            lblLD.Text = data["forecast_day3_low"];
                            lblHD.Text = data["forecast_day3_high"];
                        }
                        else
                        {
                            // -- Wind calculation --
                            string wind = data["current_wind"];
                            int loc = wind.IndexOf("at");
                            int locUnit = wind.IndexOf("kmh");

                            int wValue = Convert.ToInt32(wind.Substring(loc + 3, wind.Length - (loc + 3) - 4));
                            double metricWind = wValue / 1.61;

                            wind = wind.Replace(wind.Substring(loc + 3, wind.Length - (loc + 3) - 4), metricWind.ToString());
                            wind = wind.Replace("kmh", "mph");
                            lblWind.Text = wind.Substring(6, wind.Length - 6);
                            // -- End of wind calculation --

                            lblTemperature.Text = data["current_tempf"];

                            lblLA.Text = Convert.ToInt32((Convert.ToInt32(data["forecast_day0_low"]) *0.55) +32).ToString();
                            lblHA.Text = Convert.ToInt32((Convert.ToInt32(data["forecast_day0_high"])  *0.55) + 32).ToString();
                            lblLB.Text = Convert.ToInt32((Convert.ToInt32(data["forecast_day1_low"])  *0.55) + 32).ToString();
                            lblHB.Text = Convert.ToInt32((Convert.ToInt32(data["forecast_day1_high"]) * 0.55) + 32).ToString();
                            lblLC.Text = Convert.ToInt32((Convert.ToInt32(data["forecast_day2_low"]) * 0.55) + 32).ToString();
                            lblHC.Text = Convert.ToInt32((Convert.ToInt32(data["forecast_day2_high"]) * 0.55) + 32).ToString();
                            lblLD.Text = Convert.ToInt32((Convert.ToInt32(data["forecast_day3_low"]) * 0.55) + 32).ToString();
                            lblHD.Text = Convert.ToInt32((Convert.ToInt32(data["forecast_day3_high"]) * 0.55) + 32).ToString();
                        }
                    }

                    string time = data["datetime"];
                    time = time.Substring(0, time.Length - 6);
                    DateTime cTime = Convert.ToDateTime(time);
                    int hour = cTime.Hour;

                    UpdateImage(pbCurrent, data["current_condition"], hour);
                    this.Icon = GetIcon(Assembly.GetExecutingAssembly().Location, IconID);
                    jumpList.ClearAllUserTasks();

                    UpdateImage(pbA, data["forecast_day0_condition"], 12);
                    IconID_FA = IconID;
                    JumpListLink jll = new JumpListLink(string.Format("http://www.google.com/ig/api?weather={0}", Properties.Settings.Default.Location), string.Format("{0}  H: {1}  L: {2}", data["forecast_day0_dow"], lblHA.Text, lblLA.Text));
                    jll.IconReference = new IconReference(Assembly.GetEntryAssembly().Location, IconID_FA);
                    jumpList.AddUserTasks(jll);

                    UpdateImage(pbB, data["forecast_day1_condition"], 12);
                    IconID_FB = IconID;
                    jll = new JumpListLink(string.Format("http://www.google.com/ig/api?weather={0}", Properties.Settings.Default.Location), string.Format("{0}  H: {1}  L: {2}", data["forecast_day1_dow"], lblHB.Text, lblLB.Text));
                    jll.IconReference = new IconReference(Assembly.GetEntryAssembly().Location, IconID_FB);
                    jumpList.AddUserTasks(jll);

                    UpdateImage(pbC, data["forecast_day2_condition"], 12);
                    IconID_FC = IconID;
                    jll = new JumpListLink(string.Format("http://www.google.com/ig/api?weather={0}", Properties.Settings.Default.Location), string.Format("{0}  H: {1}  L: {2}", data["forecast_day2_dow"], lblHC.Text, lblLC.Text));
                    jll.IconReference = new IconReference(Assembly.GetEntryAssembly().Location, IconID_FC);
                    jumpList.AddUserTasks(jll);

                    UpdateImage(pbD, data["forecast_day3_condition"], 12);
                    IconID_FD = IconID;
                    jll = new JumpListLink(string.Format("http://www.google.com/ig/api?weather={0}", Properties.Settings.Default.Location), string.Format("{0}  H: {1}  L: {2}", data["forecast_day3_dow"], lblHD.Text, lblLD.Text));
                    jll.IconReference = new IconReference(Assembly.GetEntryAssembly().Location, IconID_FD);
                    jumpList.AddUserTasks(jll);

                    jumpList.Refresh();

                    int humidity = Convert.ToInt32(lblHumidity.Text.Substring(0,lblHumidity.Text.Length -1));

                    TaskbarManager tbManager = TaskbarManager.Instance;
                    tbManager.SetProgressValue(humidity,100);

                    if ((humidity > 0) && (humidity < 50))
                    {
                        tbManager.SetProgressState(TaskbarProgressBarState.Normal);
                    }
                    else if ((humidity > 50) && (humidity < 70))
                    {
                        tbManager.SetProgressState(TaskbarProgressBarState.Paused);
                    }
                    else
                    {
                        tbManager.SetProgressState(TaskbarProgressBarState.Error);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Weather cannot be updated at this time.\n" + ex.Message, "WeatherBar 2",
                        MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
        }

        private Icon GetIcon(string assembly, int id)
        {
            Icon ico = null;
            IntPtr pointer;

            if (File.Exists(assembly))
            {
                try
                {
                    pointer = ExtractIcon(this.Handle, assembly, id);
                    if (!pointer.Equals(IntPtr.Zero))
                    {
                        ico = Icon.FromHandle(pointer);
                    }
                }
                catch
                {
                    MessageBox.Show("Error setting the correct window icon.", "WeatherBar 2",
                        MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }

            return ico;
        }

        private void RefreshTimer_Tick(object sender, EventArgs e)
        {
            pnlRefresh.Visible = true;
            DoWork();
        }

        void UpdateImage(PictureBox image, string condition, int hours)
        {
            switch (condition.ToUpper())
            {
                case "PARTLY SUNNY":
                    {
                        image.Image = Properties.Resources._34;
                        IconID = 34;
                        break;
                    }
                case "SCATTERED THUNDERSTORMS":
                    {
                        if (hours > 19)
                        {
                            image.Image = Properties.Resources._47;
                            IconID = 47;
                        }
                        else
                        {
                            image.Image = Properties.Resources._37;
                            IconID = 37;
                        }
                        break;
                    } 
                case "SHOWERS":
                    {
                        if (hours > 19)
                        {
                            image.Image = Properties.Resources._45;
                            IconID = 45;
                        }
                        else
                        {
                            image.Image = Properties.Resources._39;
                            IconID =39;
                        }
                        break;
                    } 
                case "SCATTERED SHOWERS":
                    {
                        if (hours > 19)
                        {
                            image.Image = Properties.Resources._45;
                            IconID = 45;
                        }
                        else
                        {
                            image.Image = Properties.Resources._39;
                            IconID = 39;
                        }
                        break;
                    } 
                case "RAIN AND SNOW":
                    {
                        image.Image = Properties.Resources._05;
                        IconID = 5;
                        break;
                    } 
                case "OVERCAST":
                    {
                        image.Image = Properties.Resources._26;
                        IconID = 26;
                        break;
                    } 
                case "LIGHT SNOW":
                    {
                        if (hours > 19)
                        {
                            image.Image = Properties.Resources._46;
                            IconID = 46;
                        }
                        else
                        {
                            image.Image = Properties.Resources._13;
                            IconID = 13;
                        }
                        break;
                    } 
                case "FREEZING DRIZZLE":
                    {
                        image.Image = Properties.Resources._20;
                        IconID = 20;
                        break;
                    } 
                case "CHANCE OF RAIN":
                    {
                        image.Image = Properties.Resources._09;
                        IconID = 9;
                        break;
                    } 
                case "SUNNY":
                    {
                        image.Image = Properties.Resources._32;
                        IconID = 32;
                        break;
                    } 
                case "CLEAR":
                    {
                        if (hours > 19)
                        {
                            image.Image = Properties.Resources._31;
                            IconID = 31;
                        }
                        else
                        {
                            image.Image = Properties.Resources._32;
                            IconID = 32;
                        }
                        break;
                    } 
                case "MOSTLY SUNNY":
                    {
                        image.Image = Properties.Resources._34;
                        IconID = 34;
                        break;
                    } 
                case "PARTLY CLOUDY":
                    {
                        if (hours > 19)
                        {
                            image.Image = Properties.Resources._33;
                            IconID = 33;
                        }
                        else
                        {
                            image.Image = Properties.Resources._34;
                            IconID = 34;
                        }
                        break;
                    } 
                case "MOSTLY CLOUDY":
                    {
                        if (hours > 19)
                        {
                            image.Image = Properties.Resources._29;
                            IconID = 29;
                        }
                        else
                        {
                            image.Image = Properties.Resources._30;
                            IconID = 30;
                        }
                        break;
                    } 
                case "CHANCE OF STORM":
                    {
                        image.Image = Properties.Resources._00;
                        IconID = 0;
                        break;
                    } 
                case "RAIN":
                    {
                        image.Image = Properties.Resources._12;
                        IconID = 12;
                        break;
                    } 
                case "CHANCE OF SNOW":
                    {
                        image.Image = Properties.Resources._13;
                        IconID = 13;
                        break;
                    } 
                case "CLOUDY":
                    {
                        image.Image = Properties.Resources._26;
                        IconID = 26;
                        break;
                    } 
                case "MIST":
                    {
                        image.Image = Properties.Resources._20;
                        IconID = 20;
                        break;
                    } 
                case "STORM":
                    {
                        image.Image = Properties.Resources._00;
                        IconID = 0;
                        break;
                    } 
                case "THUNDERSTORM":
                    {
                        image.Image = Properties.Resources._00;
                        IconID = 0;
                        break;
                    } 
                case "CHANCE OF TSTORM":
                    {
                        image.Image = Properties.Resources._00;
                        IconID = 0;
                        break;
                    } 
                case "SLEET":
                    {
                        image.Image = Properties.Resources._25;
                        IconID = 25;
                        break;
                    } 
                case "SNOW":
                    {
                        image.Image = Properties.Resources._42;
                        IconID = 42;
                        break;
                    } 
                case "ICY":
                    {
                        image.Image = Properties.Resources._25;
                        IconID = 25;
                        break;
                    } 
                case "DUST":
                    {
                        image.Image = Properties.Resources._19;
                        IconID = 19;
                        break;
                    } 
                case "FOG":
                    {
                        image.Image = Properties.Resources._20;
                        IconID = 20;
                        break;
                    } 
                case "SMOKE":
                    {
                        image.Image = Properties.Resources._22;
                        IconID = 22;
                        break;
                    } 
                case "HAZE":
                    {
                        image.Image = Properties.Resources._21;
                        IconID = 21;
                        break;
                    } 
                case "FLURRIES":
                    {
                        image.Image = Properties.Resources._41;
                        IconID = 41;
                        break;
                    } 
                case "LIGHT RAIN":
                    {
                        image.Image = Properties.Resources._11;
                        IconID = 11;
                        break;
                    }
                default:
                    {
                        image.Image = Properties.Resources.NA;
                        IconID = 48;
                        break;
                    }
            }
        }

        private void pictureBox16_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void pictureBox15_Click(object sender, EventArgs e)
        {
            About about = new About();
            RefreshTimer.Enabled = false;
            about.ShowDialog();
            RefreshTimer.Enabled = true;
        }
    }
}
